package com.funo.logic.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.funo.logic.model.SingleOperateConfig;
import com.funo.logic.response.HandleResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * 单数据新增更新配置
 * @since 2024年7月22日15:22:17
 * @author cms
 */
@RestController
@RequestMapping("singleOperateConfig")
public class SingleOperateConfigController extends AbstractController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 配置单条数据操作
     * @param singleOperateConfig
     * @return HandleResult
     * @since 2024年7月22日16:06:01
     */
    @PostMapping("saveOrUpdate")
    public HandleResult saveOrUpdate(@RequestBody SingleOperateConfig singleOperateConfig) {
        String cacheKey = getCacheKey(singleOperateConfig.getBelongNodeId());
        stringRedisTemplate.delete(cacheKey);
        if (CollectionUtil.isNotEmpty(singleOperateConfig.getConditionList())) {
            singleOperateConfig.getConditionList().forEach(condition -> {
                String[] nameCode = condition.getRequestParam().split("/");
                condition.setName(nameCode[0]);
                condition.setCode(nameCode[1]);
                condition.setBelongNodeId(singleOperateConfig.getBelongNodeId());
            });
        }
        stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(singleOperateConfig));
        return HandleResult.success();
    }

    /**
     * 根据模块id查询配置
     * @param belongNodeId 所属模块id
     * @return HandleResult
     * @since 2024年7月22日16:06:22
     */
    @GetMapping("getByBelongNodeId")
    public HandleResult getByBelongNodeId(@RequestParam String belongNodeId) {
        String cacheKey = getCacheKey(belongNodeId);
        String value = stringRedisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(value)) {
            return HandleResult.noData();
        }
        return HandleResult.success(JSONUtil.toBean(value, SingleOperateConfig.class));
    }

    @Override
    public String getCachePrefix() {
        return "singleOperateConfig:";
    }
}
